[Music]
Welcome to Promises. After watching this video, you will be able
to: Define promises. Explain the different states of a promise and describe how to use promises with asynchronous
methods. A promise is an object returned by an asynchronous
method. The promise has three states, which are pending,
resolved, and rejected. Promises are most useful for application programming
interface (API) requests, input/output (I/O) operations, and other operations that are
time consuming and can block resources. A method can be defined to return a promise
object, if you know it is going to take time for execution and thereby block resources. When you call a method that returns a promise,
a promise object is created. The initial state of the promise is the pending
state. It is in this state until the operation is
complete or some error has caused the operation to abort. When the operation is complete, the promise
is said to be resolved. When there is an error, the promise is said
to be rejected. You can also create a promise object if you
know that the operations you are going to perform could be blocking. In this example, methCall is a promise which
is fulfilled or rejected depending on whether the file is successfully read or not. You can see on the output screen that the
content of the file is read if the filename is valid and displayed. In this case the promise is resolved. If the filename is invalid, the promise is
rejected and the error message is displayed. You know that hypertext transfer protocol
(HTTP) requests when called synchronously can be blocking. There are many packages in the Node.js ecosystem
that wrap promises around HTTP requests. The axios package is one such package to handle
HTTP requests. It returns a promise object. The status of the promise until it hears back
from the uniform resource locator (URL) requested is pending. The promise object has a "then" method which
is called after the promise is fulfilled. The catch is executed if the promise is rejected. In this example, you first pass a valid URL. It creates a pending promise. Once the promise is fulfilled, then the response
is logged on the console. Next, you pass an invalid URL. This also creates a promise object which is
pending. This promise will be rejected. This state is being dealt with in the catch
block. You can see the console log for the resolve
and reject. In this video you learned that: A promise is an object that is returned by
an asynchronous method. The initial state of the promise object is
the pending state. The axios package is used in Node.js to handle
HTTP requests and you can create a promise if you know that
the operations could be blocking.